import $ from 'jquery'
import config from '../configs/index'
import { json } from 'body-parser';
var crypto = require('crypto');

const appKey = config.appkey;
const postUrl = "https://api.netease.im";
const appSecret = config.appSecret;

/**
 *校验和
 */
function checksum(){
    const aa=[];
    for(var i=0;i<arguments.length;i++)aa.push(arguments[i]);
    const line =  aa.join("");
    console.log(line);
    return crypto.createHash('sha1').update(line).digest('hex').toLowerCase();
}

/**
 * 创建im的token 
 * @param {*} accid  登陆账号
 * @param {*} name 登录名
 * @param {*} callback 回调函数 
 */
function create_im_token(accid, name) {
    return new Promise((resolve, reject) => {
        const url = `${postUrl}/nimserver/user/create.action`;
        const time = (new Date().getTime()/1000).toFixed(0)+"";
        const nonce = (Math.random()+"").replace(".","");
        $.ajax({
            url: url,
            method:"post",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "AppKey": appKey,
                "Nonce": nonce,
                "CurTime": time,
                "CheckSum": checksum(appSecret,nonce,time) 
            },
            data: { accid: accid, token: accid,name:name },
            success: (data) => {
               resolve(data); 
            }
        });
    });
}

exports.create_im_token = create_im_token;

/**
 * 创建im的token 
 * @param {*} accid  登陆账号
 * @param {*} callback 回调函数 
 */
function refresh_im_token(accid) {
    return new Promise((resolve, reject) => {
        const url = `${postUrl}/nimserver/user/create.action`;
        const time = (new Date().getTime()/1000).toFixed(0)+"";
        const nonce = (Math.random()+"").replace(".","");
        $.ajax({
            url: url,
            method:"post",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "AppKey": appKey,
                "Nonce": nonce,
                "CurTime": time,
                "CheckSum": checksum(appSecret,nonce,time) 
            },
            data: { accid: accid },
            success: (data) => {
               resolve(data); 
            }
        });
    });
}

exports.refresh_im_token = refresh_im_token;